// ------------------------------------
// require
// ------------------------------------
import {
  HttpProxy
} from '../../../http/http-proxy';
import {
  AppConsts
} from '../../../store/appConsts'

// ------------------------------------
// Constants
// ------------------------------------
export const LOGIN_SUBMIT = "LOGIN_SUBMIT";

// ------------------------------------
// Actions
// ------------------------------------
export function loginAsync(user, pwd) {

  return (dispatch, getState) => {
    return new Promise(resolve => {
      HttpProxy.post(AppConsts.remoteApiUrl + 'api/TokenAuth/Authenticate', {
        "userNameOrEmailAddress": user,
        "password": pwd,
        "twoFactorVerificationCode": "",
        "rememberClient": true,
        "twoFactorRememberClientToken": "",
        "singleSignIn": true,
        "returnUrl": ""
      }).then(d => {
        console.log(d)
        dispatch({
          type: LOGIN_SUBMIT,
          payload: d
        });
        resolve();
      }).catch((e) => {
        resolve();
      });
    })
  };

}

export const actions = {
  loginAsync
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [LOGIN_SUBMIT]: (state, action) => (Object.assign({ ...state,
    logined: !!action.payload.success
  }, action.payload))
};

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
  logined: false
}

export default function loginReducer(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type];
  return handler ? handler(state, action) : state;
}
